<?php
namespace app\index\controller;

use app\api\controller\PlayerAuth;
use app\api\job\ChannelUploadRole;
use app\api\job\PlayerReport;
use app\common\controller\IndexBase;
use app\common\model\Channel;
use app\common\model\Order;
use app\common\model\Player as PlayerModel;
use app\common\model\PlayerRole;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use think\Queue;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Player extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $password = get_encrypt($data['password']);
            $old_password = get_encrypt($data['old_password']);

            $where['id'] = $this->uid;
            $result = PlayerModel::where($where)->find();
            if ($result['password'] != $old_password) {
                $this->error('原密码错误');
            }
            $result = PlayerModel::where($where)->update(['password' => $password]);
            if ($result) {
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }
        }
    }

    /**
     * 忘记密码，重置密码
     */
    public function forgetPassword()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $phone = $data['phone'];
            $code = $data['code'];
            $password = get_encrypt($data['password']);
            if(!checkSms($phone,$code)){
                $this->error('验证码错误');
            }
            $where['account'] = $data['phone'];
            $result = PlayerModel::where($where)->find();
            if(empty($result)){
                $this->error('账号不存在');
            }
            $where['account'] = $phone;
            $result = PlayerModel::where($where)->update(['password' => $password]);
            if ($result) {
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }
        }
    }

    /**
     * @return int
     */
    public function  createRole()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if(empty($data['sign'])){
                $this->error('sign不能为空');
            }
            $cid = $data['cid'];
            unset($data['cid']);
            unset($data['token']);
            if(!$this->checkSign($data)){
                $this->error('签名错误');
            }
            if(empty($data['role_id'])){
                $this->error('role_id不能为空');
            }

            $data['uid'] = $data['uid'] ?? $this->uid;
            $data['gid'] = $this->gid;
            $data['cid'] = $cid;
            $is_save = 0; // 创建角色
            $role = PlayerRole::where(['uid'=>$data['uid'],'gid'=>$data['gid'],'role_id'=>$data['role_id']])->find();
            if(!empty($role)){
                $is_save = 1;// 更新
                $role->role_name = $data['role_name'] ?? $role->role_name;
                $role->role_level = $data['role_level'] ?? $role->role_level;
                $role->role_power = $data['role_power'] ?? $role->role_power;
                $result = $role->save();
            }else{
                $role = $result = PlayerRole::create_role($data);
            }

            // 添加到队列
            $cid_arr = [5];
            if(in_array($cid,$cid_arr)){
                //添加redis队列、通知到游戏
                Queue::push(ChannelUploadRole::class, ['role' => json_encode($role)]);
            }
            if ($result) {
                $this->success('修改成功',"",['is_save'=>$is_save]);
            } else {
                $this->error('修改失败');
            }
        }
    }


    public function playerAuth(){
        $params = $this->request->param();
        if(empty($params['token'])){
            $this->error('token不能为空');
        }

        if(empty($params['name'])){
            $this->error('姓名不能为空');
        }
        if(empty($params['idnum'])){
            $this->error('姓名不能为空');
        }
        $where['real_name'] = trim($params['name']);
        $where['id_card'] = trim($params['idnum']);
        $token = $params['token'];
        $ip = $this->request->ip();
        if(stripos($ip,"59.82") === false){
            //实名认证
            $count_where[] = ['request_ip','=',$ip];
            $count_where[] = ['create_time','between',[date('Y-m-d 00:00:00',time()),date('Y-m-d 23:59:59',time())]];
            $ip_count = DB::connect('db_config_aiqi')->name('real_auth_log')
                ->where($count_where)
                ->count();
            if($ip_count > 10){
                echo json_encode(['code'=>"1006",'msg'=>'ip requested too many.']);exit;
            }
        }

        //查询是否实名认证
        $auth = DB::connect('db_config_aiqi')->name('real_auth')
            ->where($where)
            ->find();
        if($auth == null){
            log::info('实名认证用户数据：' . json_encode($params));
            $check = new PlayerAuth();
            $result = $check->checkIdCard($params['name'],$params['idnum']);
            log::info('实名认证返回数据：' . json_encode($result));
            //记录日志
            $auth_log = [
                "uid"=>$this->uid,
                "real_name"=>trim($params['name']),
                "id_card"=>trim($params['idnum']),
                "request_ip"=>$ip,
            ];
            DB::connect('db_config_aiqi')->name('real_auth_log')->insert($auth_log);

            if($result['errcode'] > 0){
                $this->error('实名认证失败');
                exit;
            }
            if($result['data']['result']['status'] > 0){
                $this->error('实名认证失败');
                exit;
            }
            $auth_log['pi'] = $result['data']['result']['pi'];
            DB::connect('db_config_aiqi')->name('real_auth')->insert($auth_log);
        }else{
            //记录日志
            $auth_log = [
                "uid"=>$this->uid,
                "real_name"=>trim($params['name']),
                "id_card"=>trim($params['idnum']),
                "request_ip"=>$ip,
            ];
            DB::connect('db_config_aiqi')->name('real_auth_log')->insert($auth_log);
        }
        $idInfo = getIDCardInfo($params['idnum']);
        //更新用户实名认证状态
        $this->player->is_age = $idInfo['isAdult'] ? 2 : 1;
        $this->player->age = $idInfo['age'];
        $this->player->save();

        //  更新redis
        if($token){
            $redis = new Redis();
            $redis->set($token,$this->player);
        }
        $pi = $auth['pi'] ?? $result['data']['result']['pi'];
        //添加redis队列、通知到游戏
        $collections = [
            'no'=>1,
            'bt'=>1,  ///游戏用户行为类型 0：下线 1：上线
            'ct'=>0,  ///用户行为数据上报类型 0：已认证通过用户 2：游客用户
            'di'=>md5($pi),
            'pi'=>$pi,
            'ot'=> time(),
        ];
        Queue::push(PlayerReport::class, json_encode($collections));

        $this->success('认证成功');
    }

    /**
     * 通过token获取redis的player信息
     */
    public function getPlayer()
    {
        $token = $this->request->param('token');
        $gid = $this->request->param('gid');
        if(empty($token)){
            echo json_encode(["code"=>1,"msg"=>"token不能为空"]);exit;
        }

        $redis = new Redis();
        $player = $redis->get($token);

        if(empty($player)){
            $player = Session::get("palyerinfo");
            if(empty($player)){
                echo json_encode(["code"=>1,"msg"=>"登录已失效，请重新登录"]);exit;
            }

        }

        $return = [
            'uid' => $player['id'],
            'account' => $player['account'],
            'token'=> $token,
            'is_old' => 0,
            'login_time' => $player['login_time']
        ];

        $grr = [30];
        if(in_array($gid, $grr)){
            $account = substr($player['account'],2);

            $player_old = DB::connect('db_config_aiqi')->name('player_old')->where(['gd_id'=>$account])->find();
            if(!empty($player_old)){
                $return['uid'] = $player_old['banma_id'];
                $return['is_old'] = 1;
            }
        }

        $old_grr = [81,82,83,84,85,86,87,88,86,91,
                    92,93,94,95,96,97,98,99,100,101,102];
        if(in_array($gid, $old_grr)){
            $account = substr($player['account'],2);
            $player_old = DB::connect('db_config_aiqi')->name('jinling_palyer')->where(['gd_id'=>$account])->find();
            if(!empty($player_old)){
                $return['uid'] = $player_old['old_id'];
                $return['is_old'] = 1;
            }
        }
        echo json_encode(["code"=>0,"msg"=>"获取成功","data"=>$return]);exit;
    }

    /**
     * 用户登录心跳
     */
    public function updatePlayerLoginTime(){
        Log::close();
        $params = $this->request->param();
        //添加redis,上报数据 高德
        // 动态加载自定义类（例如：app\common\CustomClass
        //手动调用示例
        $cid_arr = [5];
        if( in_array($params['cid'],$cid_arr)){
            $className ="app\index\channel\\".$this->channelName; // 替换为你的类名
            $gameapi = new $className();
            $res = $gameapi->push_report($params['rp_token']);
        }
        $params['time'] = time();
        $redis = new Redis();
        $res = $redis->get($params['token']);

        if(!empty($res)){
            // 每次上更新游戏时长
            $res['update_time'] = time();
            $redis->set($params['token'],$res);
            $this->success('更新成功');
        }
        $this->error('更新失败');

    }

    public function send_order(){
        $order_no = $this->request->param('order_no');
        $order = Order::where('order_no', $order_no)->find();
        $channel = Channel::where('id', $order->cid)->find();
        // 动态加载自定义类（例如：app\common\CustomClass
        $className ="app\index\channel\\". ucfirst($channel['username']);; // 替换为你的类名
        if (!class_exists($className)) {
            Log::info("渠道类初始化失败");
        }
        //自动注册
        $gameapi = new $className();
        $res = $gameapi->order_report($order);
    }



    public function submitReport()
    {
        $params = $this->request->param();

        if (empty($params['reportType']) || !isset($params['reportType'])) {
            $this->error('请选择问题类型');
        }
        if(empty($params['desc'])){
            $this->error('请输入问题描述');
        }
        if(strlen($params['desc']) < 10){
            $this->error('问题描述最少10个字');
        }
        if(in_array($params['reportType'],[1,2,3,4])){
            if(empty($params['server'])){
                $this->error('请选择区服');
            }
            if(empty($params['character'])){
                $this->error('请输入角色名');
            }
            if(empty($params['time'])){
                $this->error('请选择时间');
            }
        }
        if($params['reportType'] == 3){
            if(empty($params['bankuai'])){
                $this->error('请输入bug模块');
            }
            if(empty($params['shebei'])){
                $this->error('请输入设备型号');
            }
            if(empty($params['system'])){
                $this->error('请输入设备型号系统');
            }
        }
       if($params['reportType'] == 4){
           if(empty($params['status'])){
               $this->error('请选择举报类型');
           }
        }
        if($params['reportType'] == 5){
            if(empty($params['desc'])){
                $this->error('请输入问题描述');
            }
        }

        // 判断是否有处理中
        $count = DB::connect('db_config_aiqi')
            ->name('customer_services')
            ->where(['uid'=>$params['uid']])
            ->whereIn('status',[0,1])
            ->count();
        if($count > 0){
            $this->error('有处理中，请稍后重试');
        }
        $add_data= [
            'uid' => $params['uid'],
            'type'=>$params['reportType'],
            'content'=>json_encode($params),
            'create_time'=>date("Y-m-d H:i:s"),
        ];
        DB::connect('db_config_aiqi')->name('customer_services')->insert($add_data);
        $this->success('提交成功');
    }







}